import cv2
import numpy as np

if __name__ == '__main__':
    # 图片输入
    path = 'work4.jpg'
    image_np = cv2.imread(path)

    # no_noise_np = cv2.medianBlur(image_np, 3)
    # no_noise_np = cv2.GaussianBlur(image_np, (5, 5), 1)
    # no_noise_np = cv2.bilateralFilter(image_np, 5, 80, 80)
    image_np_gray = cv2.cvtColor(image_np, cv2.COLOR_BGR2GRAY)

    ret, image_np_thresh = cv2.threshold(image_np_gray, 127, 255, cv2.THRESH_OTSU + cv2.THRESH_BINARY)
    # kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3))
    # image_np_thresh = cv2.erode(image_np_thresh, kernel=kernel)
    no_noise_np = cv2.medianBlur(image_np_thresh, 3)
    # kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3))
    # image_np_thresh = cv2.dilate(image_np_thresh,kernel=kernel)
    # image_np_thresh = cv2.erode(image_np_thresh, kernel= kernel)

    # 梯度处理方式
    # 构建卷积核（水平边缘，垂直梯度）
    kernel = np.array(
        [[-1, -2, -1],
         [0, 0, 0],
         [1, 2, 1]]
    )
    print(kernel)

    dst_image1 = cv2.filter2D(
        no_noise_np,
        -1,
        kernel
    )
    kernel = np.array(
        [[-1, 0, 1],
         [-2, 0, 2],
         [-1, 0, 1]]
    )
    print(kernel)

    # 边缘提取计算
    dst_image2 = cv2.filter2D(
        no_noise_np,
        -1,
        kernel
    )


    cv2.imshow('dst_image', dst_image1)
    cv2.imshow('dst_image', dst_image2)
    cv2.imwrite('zuoye4shuiping.jpg', dst_image1)
    cv2.imwrite('zuoye4chuizhi.jpg', dst_image2)

    cv2.waitKey(0)
